#pragma once

#include <iostream>
#include <string>
#include <cstdio>
#include <set>
#include "inetAddr.hpp"
#include "Log.hpp"
class Command
{
public:
    Command() 
    {
        _whiteListCmd.insert("ls");
        _whiteListCmd.insert("pwd");
        _whiteListCmd.insert("ls -l");
        _whiteListCmd.insert("touch hh.txt");
        _whiteListCmd.insert("who");
        _whiteListCmd.insert("whoami");
    }

    bool IsSafeCmd(const std::string &cmd)
    {
        auto iter = _whiteListCmd.find(cmd);
        return iter != _whiteListCmd.end();
    }

    std::string Excute(const std::string &cmd, InetAddr &addr)
    {
        if(!IsSafeCmd(cmd))
        {
            return std::string("what do you want????");
        }

        std::string who = addr.StringAddr();

        FILE* fp = popen(cmd.c_str(), "r");
        if(nullptr == fp)
        {
            return std::string("cmd???");
        }
        std::string res;
        char line[1024];
        while(fgets(line, sizeof(line), fp))
        {
            res += line;
        }
        pclose(fp);
        std::string log = who + " do " + cmd + " result: \n" + res;
        LOG(LogLevel::INFO) << log;
        return res;
    }
    ~Command() {}
private:
    // 受限制的远程执行 
    std::set<std::string> _whiteListCmd;
};